package com.yuyang.gulimall.search.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yuyang.common.constant.ElasticConstants;
import com.yuyang.common.to.es.SkuEsModel;
import com.yuyang.gulimall.search.config.ElasticSearchConfig;
import com.yuyang.gulimall.search.service.ElasticSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yu yang
 * @date 2023/1/7 -22:55
 */
@Slf4j
@Service
public class ElasticSaveServiceImpl implements ElasticSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public boolean productStartUp(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(ElasticConstants.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String toJSONString = JSONObject.toJSONString(skuEsModel);
            indexRequest.source(toJSONString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse responses = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
//        TODO 批量保存出错
        boolean b = responses.hasFailures();
        List<String> collect = Arrays.stream(responses.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("es保存商品成功{}",collect);
        return b;
    }
}
